﻿(function(){
	/**
	 * 摇一摇
	 * @author rubekid 
	 */
	
	function Shake(options){
		this.init(options);
	}
	
	Shake.prototype = {
		init:function(options){
			options = options || {};
			var x=0, y=0, z=0,_x=0,_z=0,_y=0;
			var t=_t=(new Date()).getTime();		
			if(window.DeviceMotionEvent){
				window.addEventListener("devicemotion", deviceMotionHandler, false);
			}
			else{
				alert("该浏览器不支持摇一摇，请换个浏览器试试！");
			}
			
			function deviceMotionHandler(event){
				t = (new Date()).getTime();
				var diffTime = t - _t;
				if(diffTime < 100){//取时间大于0.1秒的变化
					return ;
				}
								
				var acceleration = event.accelerationIncludingGravity; 
				x = acceleration.x;   
				y = acceleration.y;     
				z = acceleration.z;
				var speed = Math.ceil( Math.abs(( x - _x) + ( y - _y) + ( z - _z )) / diffTime * 100 * 100 );
				
				//保存上一次记录
				_x = x;
				_y = y;
				_z = z;
				_t = t;
				
				if(typeof options.afterShake == "function"){
					options.afterShake(speed, acceleration);
				}
			}
		}
	};

	window.Shake = Shake;
	
})();
